package com.qf.j2105.shiro;

import com.qf.j2105.service.LoginService;
import com.qf.j2105.vo.LoginInfo;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.SimpleByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

public class MyRealm extends AuthorizingRealm {
    @Autowired
    private LoginService loginService;
//    授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
//    认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
       //获取用户信息
        Object principal = authenticationToken.getPrincipal();
        System.out.println("principal = " + principal);
        if (!ObjectUtils.isEmpty(principal)){
            LoginInfo loginInfo = loginService.selectByUtel((String) principal);
            System.out.println("loginInfo = " + loginInfo);
            if (loginInfo.getEname()!=null){
                System.out.println("loginInfo = " + loginInfo);
                ByteSource byteSource = new SimpleByteSource(loginInfo.getEname());
                SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(principal,loginInfo.getUpass(),byteSource,this.getName());
                return authenticationInfo;
            }
        }
        return null;
    }
}
